<?php

namespace App\Common\Utils;

//use Jaq\Request\V20161123 as Jaq;

/*
 * 此类为公共
 * * */

class Common
{

    //获取制定客户端唯一编码
    public static function getSessionToken($makeToken)
    {
        if (is_object($makeToken)) {
            $makeToken = (array)$makeToken;
        }
        $_token = '';
        foreach ($makeToken as $key => $val) {
            $_token = $val;
            break;
        }
        return $_token;
    }

    //滑动验证
    public static function slideVerification($data)
    {
        date_default_timezone_set("utc");
        include public_path() . '/backend/aliyun-safe/aliyun-php-sdk-core/Config.php';
        $key = Config()->get('verification.key');
        $secret = Config()->get('verification.secret');
        $iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", $key, $secret);
        $client = new \DefaultAcsClient($iClientProfile);
        $request = new Jaq\AfsCheckRequest();
        $request->setSession($data['csessionid']); // 必填参数，从前端获取，不可更改
        $request->setToken($data['token']); // 必填参数，从前端获取，不可更改
        $request->setSig($data['sig']); // 必填参数，从前端获取，不可更改
        $request->setScene($data['scene']); // 必填参数，从前端获取，不可更改
        $request->setPlatform(3); //必填参数，请求来源： 1：Android端； 2：iOS端； 3：PC端及其他
        $response = $client->doAction($request);
        $body = $response->getBody();
        return json_decode($body, true);
    }

    public static function getIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } elseif (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } elseif (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
            $ip = getenv("REMOTE_ADDR");
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = "unknown";
        }
        return ($ip);
    }

    public static function success($status)
    {
        \Session::flash('success', "$status");
//        $script = '
//            <script>
//            var index = parent.layer.getFrameIndex(window.name);
//            parent.layer.close(index);
//            parent.location.reload()
//       </script>'; //主要方法
//        echo $script;
    }

    public static function error($status)
    {
        \Session::flash('error', "$status");
        $script = '<script>
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
            parent.location.reload()
        </script>'; //主要方法
        echo $script;
    }

    public static function uploadImage($file)
    {
        $image = $file['file'];
        if (!isset($file['file'])) {
            return [
                'code'    => 500,
                'message' => 'file does not exist'
            ];
        }
        if ($image) {
            date_default_timezone_set('Asia/Shanghai');
            $dir = $dir = public_path() . "/upload/images/" . date('Y') . "/" . date("m") . "/" . date('d');
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $hostUrl = $_SERVER['HTTP_HOST'];
            $targetFolder = '/';
            if (!empty($_FILES)) {
                $files = $_FILES['file']['name'];
                $file_name = $files; //文件名称
                $filenames = explode(".", $file_name);

                $tempFile = $_FILES['file']['tmp_name'];
                $rand = time();
                $targetPath = $dir . '/' . ltrim($targetFolder, '/'); //图片存放目录
                $targetFile = rtrim($targetPath, '/') . '/' . $rand . "." . $filenames[count($filenames) - 1]; //图片完整路徑
                $fileTypes = array('jpg', 'jpeg', 'png'); // File extensions
                $fileParts = pathinfo($_FILES['file']['name']);
                $output_file = $hostUrl . "/upload/images/" . date('Y') . "/" . date("m") . "/" . date('d') . "/" . $rand . "." . $filenames[count($filenames) - 1];
                if (in_array($fileParts['extension'], $fileTypes)) {
                    move_uploaded_file($tempFile, $targetFile);
                    return [
                        'code' => 200,
                        'url'  => $output_file,
                        'path' => "/upload/images/" . date('Y') . "/" . date("m") . "/" . date('d') . "/" . $rand . "." . $filenames[count($filenames) - 1],
                        'name' => $rand . "." . $filenames[count($filenames) - 1]
                    ];
                } else {
                    return [
                        'code'    => 500,
                        'message' => 'is error'
                    ];
                }
            }
        }
    }

    public static function isHttp()
    {

        if (defined('HTTPS') && HTTPS)
            return true;
        if (!isset($_SERVER))
            return FALSE;
        if (!isset($_SERVER['HTTPS']))
            return FALSE;
        if ($_SERVER['HTTPS'] === 1) {  //Apache
            return TRUE;
        } elseif ($_SERVER['HTTPS'] === 'on') { //IIS
            return TRUE;
        } elseif ($_SERVER['SERVER_PORT'] == 443) { //其他
            return TRUE;
        }
        return FALSE;
    }

    public static function getHost()
    {
        return (self::isHttp() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
    }

    public static function page($query, $page = 1, $limit = 15)
    {
        $page = $page - 1;
        if ($page != 0) {
            $page = $limit * $page;
            $limit = $limit * $page;
        }
        $cloneQuery = (clone $query);
        $totalCount = $cloneQuery->count();
        $datas = $cloneQuery->offset($page)->limit($limit)->get()->toArray();
        return [
            'pageCount'  => ceil($totalCount / $limit),
            'totalCount' => $totalCount * 1,
            'list'       => $datas
        ];
    }

}
